/**
 * (created at 2011-2-18)
 */
package qiushuo.mysqlparser.recognizer.parser;

import static qiushuo.mysqlparser.recognizer.SQLTokenType.IDENTIFIER;
import static qiushuo.mysqlparser.recognizer.SQLTokenType.KW_CALL;
import static qiushuo.mysqlparser.recognizer.SQLTokenType.PUNC_LEFT_PAREN;
import static qiushuo.mysqlparser.recognizer.SQLTokenType.PUNC_RIGHT_PAREN;

import java.sql.SQLSyntaxErrorException;
import java.util.LinkedList;
import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.statement.DMLCallStatement;
import qiushuo.mysqlparser.recognizer.SQLToken;
import qiushuo.mysqlparser.recognizer.TokenReader;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class DMLCallParser extends DMLParser {
    public DMLCallParser(TokenReader input) {
        super(input);
    }

    /** nothing has been pre-consumed */
    public DMLCallStatement call() throws SQLSyntaxErrorException {
        match(KW_CALL);
        String name = match(IDENTIFIER).getText();
        match(PUNC_LEFT_PAREN);
        if (input.isNext(PUNC_RIGHT_PAREN, 0)) {
            input.skipForce(1);
            return new DMLCallStatement(name, null);
        }
        List<Expression> args = new LinkedList<Expression>();
        while (true) {
            Expression arg = exprParser.expression();
            args.add(arg);
            SQLToken t = input.next();
            if (t == null) throw err("EOF for CALL args");
            switch (t.getType()) {
            case PUNC_COMMA:
                continue;
            case PUNC_RIGHT_PAREN:
                return new DMLCallStatement(name, args);
            default:
                throw err("unexpected token for CALL args: " + t);
            }
        }
    }
}
